package com.loyal.qr.zbar;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;

import com.loyal.qr.CodeUtil;
import com.loyal.qr.R;

/**
 * 一维码/条形码
 */
public class BarCodeView extends View {
    private final Paint mBmpPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private final TextPaint mTextPaint = new TextPaint();
    private Resources resources;
    private Bitmap bitmap;

    private StaticLayout textLayout;
    private Rect textRect=new Rect();
    private String barContent;
    private int textColor;
    private float textSize;
    private boolean textBold = false;

    public BarCodeView(Context context) {
        super(context);
        initialize(context, null);
        initPaint();
    }

    public BarCodeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initialize(context, attrs);
        initPaint();
    }

    public BarCodeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context, attrs);
        initPaint();
    }

    private void initialize(Context context, AttributeSet attrs) {
        resources = context.getResources();
        TypedArray attributes = getContext().obtainStyledAttributes(attrs, R.styleable.BarCodeView);
        textSize = attributes.getDimension(R.styleable.BarCodeView_android_textSize, dp2px(12f));
        textColor = attributes.getColor(R.styleable.BarCodeView_android_textColor, Color.BLACK);
        barContent = attributes.getString(R.styleable.BarCodeView_android_text);
        textBold = attributes.getBoolean(R.styleable.BarCodeView_boldText, false);
        //getDimensionPixelSize()方法返回的实际数值是四舍五入的。
        //getDimensionPixelOffset返回的实际数值是去掉结果后面的小数点。
        int marginTop = attributes.getDimensionPixelSize(R.styleable.BarCodeView_textMarginTop, 0);
        int marginBottom = attributes.getDimensionPixelSize(R.styleable.BarCodeView_textMarginBottom, 0);

        int paddingTop = attributes.getDimensionPixelSize(R.styleable.BarCodeView_textPaddingTop, 0);
        int paddingBottom = attributes.getDimensionPixelSize(R.styleable.BarCodeView_textPaddingBottom, 0);
        int paddingStart = attributes.getDimensionPixelSize(R.styleable.BarCodeView_textPaddingStart, 0);
        int paddingEnd = attributes.getDimensionPixelSize(R.styleable.BarCodeView_textPaddingEnd, 0);
        attributes.recycle();
    }

    private void initPaint() {
        mBmpPaint.setColor(Color.RED);

        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextAlign(Paint.Align.CENTER);
        setContent(barContent);
        setPxTextSize(textSize);
        setTextColor(textColor);
        setBoldText(textBold);
    }

    //https://www.freesion.com/article/3629898083/
    //暂不支持wrap_content
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 获取宽-测量规则的模式和大小
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        // 获取高-测量规则的模式和大小
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        // 设置wrap_content的默认宽 / 高值
        // 默认宽/高的设定并无固定依据,根据需要灵活设置
        // 类似TextView,ImageView等针对wrap_content均在onMeasure()对设置默认宽 / 高值有特殊处理,具体读者可以自行查看
        int mWidth = contentWrapWidth();
        int mHeight = contentWrapHeight();
        Log.e("onMeasure: ", "wrapWidth=" + mWidth);
        Log.e("onMeasure: ", "wrapHeight=" + mHeight);

        int paramsWidth = getLayoutParams().width;
        int paramsHeight = getLayoutParams().height;

        // 当布局参数设置为wrap_content时，设置默认值
        if (isWrapContentMode(paramsWidth) && isWrapContentMode(paramsHeight)) {
            setMeasuredDimension(mWidth, mHeight);
            // 宽 / 高任意一个布局参数为= wrap_content时，都设置默认值
        } else if (isWrapContentMode(paramsWidth)) {
            setMeasuredDimension(mWidth, heightSize);
        } else if (isWrapContentMode(paramsHeight)) {
            setMeasuredDimension(widthSize, mHeight);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (null == bitmap || TextUtils.isEmpty(barContent))
            return;
        drawBitmap(canvas);
        drawText(canvas);
    }

    private void drawBitmap(Canvas canvas) {
        int width = getWidth();
        int bmpWidth = bitmap.getWidth();
        canvas.drawBitmap(bitmap, (width - bmpWidth) / 2f, 0f, mBmpPaint);
    }

    private void drawText(Canvas canvas) {
        int width = getWidth();
        int height = contentWrapHeight();

        mTextPaint.getTextBounds(barContent, 0, barContent.length(), textRect);
        float textWidth = textRect.width();
        float textHeight = textRect.height();

        Log.e("drawText", "textWidth ---> " + textWidth);
        Log.e("drawText", "textHeight ---> " + textHeight);

        canvas.drawText(barContent, 0, barContent.length(), width / 2f, height, mTextPaint);
    }

    public void setContent(String content) {
        setContent(content, 500, 200);
    }

    private int contentWrapWidth() {
        int bmpWidth = null == bitmap ? 0 : bitmap.getWidth();
        int txtWidth = null == textLayout ? 0 : textLayout.getWidth();
        return Math.max(bmpWidth, txtWidth);
    }

    private int contentWrapHeight() {
        int bmpHeight = null == bitmap ? 0 : bitmap.getHeight();
        //int txtHeight = null == textLayout ? 0 : textLayout.getHeight();
        int txtHeight = null == textRect ? 0 : textRect.height();
        return bmpHeight + txtHeight;
    }

    private boolean isWrapContentMode(int size) {
        return ViewGroup.LayoutParams.WRAP_CONTENT == size;
    }

    public void setContent(String content, int bmpWidth, int bmpHeight) {
        this.barContent = TextUtils.isEmpty(content) ? "" : content;

        bitmap = CodeUtil.createBarBitmap(barContent, bmpWidth, bmpHeight);

        textLayout = new StaticLayout(barContent, mTextPaint, bmpWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
        updateTextLayout();
    }

    public String getBarContent() {
        return barContent;
    }

    public void setTextSize(float textSize) {//TypedValue.COMPLEX_UNIT_PX
        this.textSize = textSize;

        setPxTextSize(dp2px(textSize));
        updateTextLayout();
    }

    private void setPxTextSize(float size) {
        float pxSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, size, resources.getDisplayMetrics());
        mTextPaint.setTextSize(pxSize);
    }

    public void setTextColor(@ColorInt int textColor) {
        this.textColor = textColor;
        mTextPaint.setColor(textColor);
        updateTextLayout();
    }

    public void setBoldText(boolean boldText) {
        mTextPaint.setFakeBoldText(boldText);
        updateTextLayout();
    }

    private void updateTextLayout(){
        mTextPaint.getTextBounds(barContent, 0, barContent.length(), textRect);
        requestLayout();
        invalidate();
    }

    public void setMargins(int left, int top, int right, int bottom) {
        /*if (null != textView) {
            LayoutParams layoutParams = (LayoutParams) textView.getLayoutParams();
            layoutParams.setMargins(left, top, right, bottom);
            textView.setLayoutParams(layoutParams);
        }*/
    }

    public static float dp2px(float dp) {
        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        return dp * metrics.density;
    }
}
